package com.xinqi.modules.chat.chat.friend.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xinqi.common.base.enums.YesNoNumberEnum;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.R;
import com.xinqi.common.base.utils.spring.Spring;
import com.xinqi.common.core.constant.CacheConstants;
import com.xinqi.common.core.constant.ChatConstants;
import com.xinqi.common.core.constant.ChatRemindConstants;
import com.xinqi.common.core.utils.MessageUtils;
import com.xinqi.common.core.utils.StringUtils;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.common.redis.utils.RedisUtils;
import com.xinqi.modules.chat.chat.friend.domain.ChatFriendEntity;
import com.xinqi.modules.chat.chat.friend.dto.req.ChatFriendListQueryDTO;
import com.xinqi.modules.chat.chat.friend.dto.req.ChatFriendUpdateDTO;
import com.xinqi.modules.chat.chat.friend.dto.rsp.*;
import com.xinqi.modules.chat.chat.friend.manager.ChatFriendManager;
import com.xinqi.modules.chat.chat.friend.service.ChatFriendService;
import com.xinqi.modules.chat.chat.group.dto.req.ConversationSelectDTO;
import com.xinqi.modules.chat.chat.group.dto.req.GroupUserFriendQueryDTO;
import com.xinqi.modules.chat.chat.group.dto.rsp.ConversationResultDTO;
import com.xinqi.modules.chat.chat.group.dto.rsp.GroupUserFriendResultDTO;
import com.xinqi.modules.chat.enums.friend.FriendStatusEnum;
import com.xinqi.modules.chat.third.rongyun.service.RongyunService;
import com.xinqi.modules.user.user.client.UserClient;
import com.xinqi.modules.user.user.dto.rsp.UserResultDTO;
import io.rong.util.CodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 好友列表服务层实现
 *
 * @author: system
 * @date: 2023/01/12
 */
@Log4j2
@Service("chatFriendService")
@RequiredArgsConstructor
public class ChatFriendServiceImpl implements ChatFriendService {

    private final ChatFriendManager chatFriendManager;

    private final RongyunService rongyunService;

    private final ChatFriendMessageService chatFriendMessageService;

    private final UserClient userClient;

    /**
     * 注册时初始化好友列表
     * @param userId :
     * @return :java.lang.Boolean
     * @Title:
     * @MethodName: initFriend
     * @Exception
     * @Description:
     * @author: yyzhen
     * @date: 2023/5/15 13:38
     */
    @Override
    public Boolean initFriend(Long userId) {
        List<ChatFriendEntity> initList = new ArrayList<>();
        //初始化自己为好友
        ChatFriendEntity own = initFriendEntity(userId, userId);
        initList.add(own);
        //初始化新奇提醒为好友
        ChatFriendEntity remind = initFriendEntity(userId, Long.parseLong(ChatRemindConstants.REMIND));
        initList.add(remind);
        //初始化新奇助手为好友
        ChatFriendEntity assistant = initAssistantEntity(userId, Long.parseLong(ChatRemindConstants.ASSISTANT));
        initList.add(assistant);

        try {
            return chatFriendManager.saveBatch(initList);
        } catch (Exception e) {
            guardInitFriend(userId);
             return Boolean.TRUE;
        }
    }

    /**
     * 注册好友列表初始化失败守护程序
     * 防止没有初始化数据对后续产生错误影响
     * @param userId
     */
    private void guardInitFriend(Long userId) {
        // 获取是否有自己 新奇提醒 新奇助手好友
        LambdaQueryWrapper<ChatFriendEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendEntity::getUserId, userId);
        wrapper.and(sonWrapper -> sonWrapper.eq(ChatFriendEntity::getFriendId, userId)
            .or(remindWrapper -> remindWrapper.eq(ChatFriendEntity::getFriendId, Long.parseLong(ChatRemindConstants.REMIND)))
            .or(assistantWrapper -> assistantWrapper.like(ChatFriendEntity::getFriendId, ChatRemindConstants.ASSISTANT)));
        List<ChatFriendEntity> list = chatFriendManager.list(wrapper);
        List<Long> friendIds = list.stream().map(ChatFriendEntity::getFriendId).collect(Collectors.toList());

        // 判断是否有自己
        if (friendIds.contains(userId)) {
            friendIds.remove(userId);
        } else {
            friendIds.add(userId);
        }
        // 判断是否有新奇提醒
        if (friendIds.contains(Long.parseLong(ChatRemindConstants.REMIND))) {
            friendIds.remove(Long.parseLong(ChatRemindConstants.REMIND));
        } else {
            friendIds.add(Long.parseLong(ChatRemindConstants.REMIND));
        }
        // 判断是否有新奇助手
        boolean assistantFlag = false;
        for (Long friendId : friendIds) {
            if (friendId.toString().contains(ChatRemindConstants.ASSISTANT)) {
                assistantFlag = true;
                friendIds.remove(friendId);
            }
        }
        if (!assistantFlag) {
            friendIds.add(Long.parseLong(ChatRemindConstants.ASSISTANT));
        }

        // 创建需新增的好友
        if (CollectionUtil.isNotEmpty(friendIds)) {
            friendIds.stream().forEach(friendId -> {
                guardInitFriend(userId, friendId);
            });
        }
    }

    /**
     * 新奇提醒、新奇助手、自己
     * @param userId
     * @param friedId
     */
    private void guardInitFriend(Long userId, Long friedId) {
        if (Objects.equals(Long.parseLong(ChatRemindConstants.REMIND), friedId)) {
            //初始化新奇提醒为好友
            ChatFriendEntity remind = this.chatFriendManager.friedByUserIdFriendId(userId, Long.parseLong(ChatRemindConstants.REMIND));
            if (Objects.isNull(remind)) {
                try {
                    this.chatFriendManager.save(initFriendEntity(userId, Long.parseLong(ChatRemindConstants.REMIND)));
                } catch (Exception e) {
                    log.info("用户 => {}，好友 => {} 数据已存在，数据库唯一校验不通过", userId, ChatRemindConstants.REMIND);
                }
            } else if (Objects.equals(YesNoNumberEnum.NO.getCode(), remind.getIsFriend())) {
                Long id = remind.getId();
                remind = initFriendEntity(userId, Long.parseLong(ChatRemindConstants.REMIND));
                remind.setId(id);
                this.chatFriendManager.updateById(remind);
            }
        }
        if (Objects.equals(Long.parseLong(ChatRemindConstants.ASSISTANT), friedId)) {
            //初始化新奇助手为好友
            ChatFriendEntity assistant = this.chatFriendManager.friedByUserIdFriendId(userId, Long.parseLong(ChatRemindConstants.ASSISTANT));
            if (Objects.isNull(assistant)) {
                try {
                    this.chatFriendManager.save(initAssistantEntity(userId, Long.parseLong(ChatRemindConstants.ASSISTANT)));
                } catch (Exception e) {
                    log.info("用户 => {}，好友 => {} 数据已存在，数据库唯一校验不通过", userId, ChatRemindConstants.ASSISTANT);
                }
            } else if (Objects.equals(YesNoNumberEnum.NO.getCode(), assistant.getIsFriend())) {
                Long id = assistant.getId();
                assistant = initAssistantEntity(userId, Long.parseLong(ChatRemindConstants.ASSISTANT));
                assistant.setId(id);
                this.chatFriendManager.updateById(assistant);
            }
        }
        if (Objects.equals(userId, friedId)) {
            //初始化自己为好友
            ChatFriendEntity own = this.chatFriendManager.friedByUserIdFriendId(userId, userId);
            if (Objects.isNull(own)) {
                try {
                    //初始化自己为好友(数据库唯一校验)
                    this.chatFriendManager.save(initFriendEntity(userId, userId));
                } catch (Exception e) {
                    log.info("用户 => {}，好友 => {} 数据已存在，数据库唯一校验不通过", userId, userId);
                }
            } else if (Objects.equals(YesNoNumberEnum.NO.getCode(), own.getIsFriend())) {
                Long id = own.getId();
                own = initFriendEntity(userId, userId);
                own.setId(id);
                this.chatFriendManager.updateById(own);
            }
        }

    }

    /**
     * 初始化好友信息
     * @param userId
     * @param friendId
     * @return
     */
    private ChatFriendEntity initFriendEntity(Long userId, Long friendId) {
        ChatFriendEntity entity = new ChatFriendEntity();
        entity.setUserId(userId);
        entity.setFriendId(friendId);
        entity.setStatus(FriendStatusEnum.ONE.getCode());
        entity.setIsFriend(YesNoNumberEnum.YES.getCode());
        entity.setStarMark(YesNoNumberEnum.NO.getCode());
        entity.setIsTop(YesNoNumberEnum.NO.getCode());
        entity.setIsDisturb(YesNoNumberEnum.NO.getCode());
        entity.setHiddenChat(YesNoNumberEnum.NO.getCode());
        return entity;
    }

    /**
     * 初始化新奇助手信息
     * @param userId
     * @param friendId
     * @return
     */
    private ChatFriendEntity initAssistantEntity(Long userId, Long friendId) {
        ChatFriendEntity entity = new ChatFriendEntity();
        entity.setUserId(userId);
        entity.setFriendId(this.checkAssistantNum(friendId));
        entity.setStatus(FriendStatusEnum.ONE.getCode());
        entity.setIsFriend(YesNoNumberEnum.YES.getCode());
        entity.setStarMark(YesNoNumberEnum.NO.getCode());
        entity.setIsTop(YesNoNumberEnum.NO.getCode());
        entity.setIsDisturb(YesNoNumberEnum.NO.getCode());
        entity.setHiddenChat(YesNoNumberEnum.NO.getCode());
        return entity;
    }

    /**
     * 获取助手最新绑定的ID
     * @return
     */
    private Long checkAssistantNum(Long friendId) {
        FriendAssistantCurrentDTO assistantCurrentDTO = RedisUtils.getCacheObject(CacheConstants.ASSISTANT_KEY);
        if (Objects.nonNull(assistantCurrentDTO)) {
            if (assistantCurrentDTO.getTotal() > 999) {
                // 注册新的助手用户
                Spring.committedAsync(()-> {
                    this.refreshAssistant();
                });
            } else {
                // 刷新绑定次数
                assistantCurrentDTO.setTotal(assistantCurrentDTO.getTotal() + 1);
                RedisUtils.setCacheObject(CacheConstants.ASSISTANT_KEY, assistantCurrentDTO);
            }
            return assistantCurrentDTO.getFriendId();
        } else {
            assistantCurrentDTO = chatFriendManager.checkCurrentAssistant();
            if (Objects.isNull(assistantCurrentDTO)) {
                // 更新Redis
                assistantCurrentDTO = new FriendAssistantCurrentDTO();
                assistantCurrentDTO.setFriendId(friendId);
                assistantCurrentDTO.setTotal(0L);
                RedisUtils.setCacheObject(CacheConstants.ASSISTANT_KEY, assistantCurrentDTO);
                return friendId;
            } else {
                if (assistantCurrentDTO.getTotal() < 1000) {
                    // 更新Redis
                    RedisUtils.setCacheObject(CacheConstants.ASSISTANT_KEY, assistantCurrentDTO);
                    return assistantCurrentDTO.getFriendId();
                } else {
                    // 注册新的助手用户
                    Spring.committedAsync(()-> {
                        this.refreshAssistant();
                    });
                    return assistantCurrentDTO.getFriendId();
                }
            }
        }
    }

    /**
     * 更新助手新用户
     * @return
     */
    private void refreshAssistant() {
        UserResultDTO user = R.as(userClient.registerAssistant());
        rongyunService.registUser(user.getId().toString(), user.getNickname(), user.getAvatar());
        FriendAssistantCurrentDTO assistant = new FriendAssistantCurrentDTO();
        assistant.setFriendId(user.getId());
        assistant.setTotal(0L);
        // 更新Redis
        RedisUtils.setCacheObject(CacheConstants.ASSISTANT_KEY, assistant);
    }

    /**
     * 检查是否是好友
     *
     * @param userId   用户Id
     * @param friendId 好友账号
     * @return
     */
    @DS("slaver")
    @Override
    public ChatFriendResultDTO friedCheck(Long userId, Long friendId) {
        return chatFriendManager.friedCheck(userId, friendId);
    }

    /**
     * 返回用户信息，并校验是否是好友
     *
     * @Title:
     * @MethodName: userInfoByUserId
     * [query]
     * @Return com.xinqi.modules.chat.chat.friend.dto.rsp.ChatFriendInfoResultDTO
     * @Exception
     * @Description:
     * @author: yyzhen
     * @date: 2023/4/10 19:43
     */
    @Override
    @DS("slaver")
    public List<ChatFriendInfoResultDTO> userInfoByUserId(ChatFriendListQueryDTO query) {
        CommonErrors.BAD_REQUEST.check(CollectionUtil.isNotEmpty(query.getFriendIds()), MessageUtils.message("user.id.not.black"));
        List<ChatFriendInfoResultDTO> list = chatFriendManager.userInfoByUserId(query);
        if (CollectionUtil.isEmpty(list)) {
            return list;
        }
        list.stream().forEach(item -> {
            if (Objects.equals(2, item.getShowInfoConfig())) {
                //手机号码脱敏
                item.setMobile(DesensitizedUtil.mobilePhone(item.getMobile()));
            } else if (Objects.equals(YesNoNumberEnum.YES.getCode(), item.getIsFriend())) {
                //手机号好友不可见
                if (Objects.equals(YesNoNumberEnum.NO.getCode(), item.getShowMobileConfig())) {
                    //手机号码脱敏
                    item.setMobile(DesensitizedUtil.mobilePhone(item.getMobile()));
                }
            } else if (Objects.equals(YesNoNumberEnum.NO.getCode(), item.getIsFriend())) {
                //手机号码脱敏
                item.setMobile(DesensitizedUtil.mobilePhone(item.getMobile()));
            }
        });
        return list;
    }

    /**
     * 获取指定用户好友列表-星标分类
     *
     * @param userId 用户Id
     * @return
     */
    @Override
    public ChatFriendListTypeResultDTO friedListStarMark(Long userId) {
        //获取普通好友列表
        ChatFriendListQueryDTO query = new ChatFriendListQueryDTO();
        query.setOperationUserId(userId);
        query.setStatus(FriendStatusEnum.ONE.getCode());
        query.setIsFriend(YesNoNumberEnum.YES.getCode());
        List<ChatFriendDetailsResultDTO> friendList = chatFriendManager.findFriendList(query);
        List<Long> friendIds = new ArrayList<>();
        friendIds.add(userId);
        friendIds.add(Long.parseLong(ChatRemindConstants.ASSISTANT));
        friendIds.add(Long.parseLong(ChatRemindConstants.REMIND));
        friendList.stream().forEach(item -> {
            friendIds.remove(item.getFriendId());
        });
        if (CollectionUtil.isNotEmpty(friendIds)) {
            friendIds.stream().forEach(friendId -> {
                guardInitFriend(userId, friendId);
            });
            friendList = chatFriendManager.findFriendList(query);
        }

        //获取星标好友列表 -- 目前业务没有星标好友
        //ChatFriendListQueryDTO startQuery = new ChatFriendListQueryDTO();
        //startQuery.setOperationUserId(userId);
        //startQuery.setStatus(FriendStatusEnum.ONE.getCode());
        //startQuery.setIsFriend(YesNoNumberEnum.YES.getCode());
        //startQuery.setStartMark(YesNoNumberEnum.YES.getCode());
        //List<ChatFriendDetailsResultDTO> startMarkFriendList = chatFriendManager.findFriendList(startQuery);
        return new ChatFriendListTypeResultDTO(friendList, new ArrayList<>());
    }

    /**
     * 好友详情
     *
     * @param userId   当前用户Id
     * @param friendId 好友Id
     * @return
     */
    @DS("slaver")
    @Override
    public ChatFriendDetailsResultDTO friedDetails(Long userId, Long friendId) {
        ChatFriendDetailsResultDTO friendDetailsResultDTO = chatFriendManager.findFriendDetail(userId, friendId);
        if (Objects.nonNull(friendDetailsResultDTO)) {
            //手机号好友不可见
            if (Objects.equals(YesNoNumberEnum.NO.getCode(), friendDetailsResultDTO.getShowMobileConfig())) {
                //手机号码脱敏
                friendDetailsResultDTO.setMobile(DesensitizedUtil.mobilePhone(friendDetailsResultDTO.getMobile()));
            }
        }

        return friendDetailsResultDTO;
    }

    /**
     * 设置好友
     *
     * @param userId 用户Id
     * @param dto    ChatFriendUpdateDTO
     * @return
     */
    @Override
    public Boolean setFriend(Long userId, ChatFriendUpdateDTO dto) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(dto.getId()), MessageUtils.message("chat.friend.id.not.blank"));
        ChatFriendEntity old = Optional.ofNullable(chatFriendManager.getOne(wrapper(userId, dto.getId()).last("LIMIT 1")))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException(MessageUtils.message("data.does.not.exist")));
        //备注可设置为空
        LambdaUpdateWrapper<ChatFriendEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(dto.getRenames() != null, ChatFriendEntity::getRenames, dto.getRenames())
            .set(StringUtils.isNotEmpty(dto.getBackground()), ChatFriendEntity::getBackground, dto.getBackground())
            .set(Objects.nonNull(dto.getHiddenChat()), ChatFriendEntity::getHiddenChat, dto.getHiddenChat())
            .set(Objects.nonNull(dto.getStarMark()), ChatFriendEntity::getStarMark, dto.getStarMark())
            //防止报错
            .set(ChatFriendEntity::getUserId, old.getUserId());
        //免打扰
        if (Objects.nonNull(dto.getIsDisturb()) && !Objects.equals(old.getIsDisturb(), dto.getIsDisturb())) {
            if (Objects.equals(YesNoNumberEnum.YES.getCode(), dto.getIsDisturb())) {
                boolean muteFlag = rongyunService.conversationDisturb(userId.toString(), old.getFriendId().toString(),
                    CodeUtil.ConversationType.PRIVATE, YesNoNumberEnum.YES.getCode());
                if (muteFlag) {
                    updateWrapper.set(Objects.nonNull(dto.getIsDisturb()), ChatFriendEntity::getIsDisturb, dto.getIsDisturb());
                }
            } else if (Objects.equals(YesNoNumberEnum.NO.getCode(), dto.getIsDisturb())) {
                boolean unMuteFlag = rongyunService.conversationDisturb(userId.toString(), old.getFriendId().toString(),
                    CodeUtil.ConversationType.PRIVATE, YesNoNumberEnum.NO.getCode());
                if (unMuteFlag) {
                    updateWrapper.set(Objects.nonNull(dto.getIsDisturb()), ChatFriendEntity::getIsDisturb, dto.getIsDisturb());
                }
            }
        }
        //置顶
        if (Objects.nonNull(dto.getIsTop()) && !Objects.equals(old.getIsTop(), dto.getIsTop())) {
            if (Objects.equals(YesNoNumberEnum.YES.getCode(), dto.getIsTop())) {
                boolean topFlag = rongyunService.conversationTop(userId.toString(), CodeUtil.ConversationType.PRIVATE.getName(),
                    old.getFriendId().toString(), true);
                if (topFlag) {
                    updateWrapper.set(Objects.nonNull(dto.getIsTop()), ChatFriendEntity::getIsTop, dto.getIsTop())
                        .set(ChatFriendEntity::getTopTime, LocalDateTime.now());
                }
            } else if (Objects.equals(YesNoNumberEnum.NO.getCode(), dto.getIsTop())) {
                updateWrapper.set(ChatFriendEntity::getTopTime, null);
                boolean unTopFlag = rongyunService.conversationTop(userId.toString(), CodeUtil.ConversationType.PRIVATE.getName(),
                    old.getFriendId().toString(), false);
                if (unTopFlag) {
                    updateWrapper.set(Objects.nonNull(dto.getIsTop()), ChatFriendEntity::getIsTop, dto.getIsTop())
                        .set(ChatFriendEntity::getTopTime, LocalDateTime.now());
                }
            }
        }
        updateWrapper.eq(ChatFriendEntity::getId, old.getId());
        return chatFriendManager.update(updateWrapper);
    }

    /**
     * 删除好友
     *
     * @param userId   userId
     * @param friendId friendId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteFriend(Long userId, Long friendId) {
        //互相删除好友
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(friendId), MessageUtils.message("chat.friend.friendId.not.blank"));
        //好友方删除（改为非好友状态）
        LambdaUpdateWrapper<ChatFriendEntity> user = Wrappers.lambdaUpdate();
        user.set(ChatFriendEntity::getIsFriend, YesNoNumberEnum.NO.getCode())
            .eq(ChatFriendEntity::getUserId, friendId)
            .eq(ChatFriendEntity::getFriendId, userId);
        chatFriendManager.update(user);
        //操作方删除（改为非好友状态）
        LambdaUpdateWrapper<ChatFriendEntity> friend = Wrappers.lambdaUpdate();
        friend.set(ChatFriendEntity::getIsFriend, YesNoNumberEnum.NO.getCode())
            .eq(ChatFriendEntity::getUserId, userId)
            .eq(ChatFriendEntity::getFriendId, friendId);
        chatFriendManager.update(friend);
        chatFriendMessageService.sendDeleteFriendMsg(userId, friendId);
         return Boolean.TRUE;
    }

    /**
     * 获取指定用户好友列表
     *
     * @param dto
     * @return
     */
    @DS("slaver")
    @Override
    public List<ChatFriendDetailsResultDTO> friedList(ChatFriendListQueryDTO dto) {
        dto.setStatus(FriendStatusEnum.ONE.getCode());
        dto.setIsFriend(YesNoNumberEnum.YES.getCode());

        List<ChatFriendDetailsResultDTO> list = chatFriendManager.findFriendList(dto);
        //Iterator 迭代器 移除好友列表中的新奇提醒、新奇助手、自己
        Iterator<ChatFriendDetailsResultDTO> it = list.iterator();
        while (it.hasNext()) {
            ChatFriendDetailsResultDTO item = it.next();
            if (Objects.equals(ChatRemindConstants.REMIND, item.getFriendId().toString())) {
                it.remove();
            } else if (Objects.equals(ChatRemindConstants.ASSISTANT, item.getFriendId().toString())) {
                it.remove();
            }
            /*else if (Objects.equals(dto.getOperationUserId(), item.getFriendId())) {
                it.remove();
            }*/
        }
        return list;
    }

    /**
     * @Title: 移除黑名单
     * @MethodName: removeChatFriendBlack
     * [friendId,operationUserId]
     * @Return java.lang.Boolean
     * @Exception
     * @Description:
     * @author: yyzhen
     * @date: 2023/3/7 14:12
     */
    @Override
    public Boolean removeChatFriendBlack(Long friendId, Long operationUserId) {
        ChatFriendEntity oldChatFriend = chatFriendManager.friedByUserIdFriendId(operationUserId, friendId);
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(oldChatFriend), MessageUtils.message("chat.friend.remove.black.fail"));

        ChatFriendEntity chatFriend = new ChatFriendEntity();
        chatFriend.setId(oldChatFriend.getId());
        chatFriend.setUserId(operationUserId);
        chatFriend.setFriendId(friendId);
        chatFriend.setStatus(FriendStatusEnum.ONE.getCode());
        //第三方融云调用
        boolean addFlag = rongyunService.blackManager(chatFriend.getUserId().toString(),
            chatFriend.getFriendId().toString(), FriendStatusEnum.ONE.getCode());
        if (addFlag) {
            chatFriendManager.updateById(chatFriend);
        }
        return addFlag;
    }

    /**
     * 加入黑名单
     *
     * @Title:
     * @MethodName: addChatFriendBlack
     * [userId, operationUserId]
     * @Return java.lang.Boolean
     * @Exception
     * @Description:
     * @author: yyzhen
     * @date: 2023/3/24 13:58
     */
    @Override
    public Boolean addChatFriendBlack(Long userId, Long operationUserId) {
        //黑名单上限100人
        Long blackCount = chatFriendManager.selectCountBlack(operationUserId);
        if (Objects.nonNull(blackCount) && blackCount >= ChatConstants.CHAT_BLACK_FRIEND_LIMIT) {
            CommonErrors.BAD_REQUEST.check(false, MessageUtils.message("chat.friend.black.upper.limit"));
        }


        //第三方融云调用
        boolean removeFlag = rongyunService.blackManager(operationUserId.toString(),
            userId.toString(), FriendStatusEnum.TWO.getCode());
        if (removeFlag) {
            ChatFriendEntity oldChatFriend = chatFriendManager.friedByUserIdFriendId(operationUserId, userId);
            if (Objects.isNull(oldChatFriend)) {
                ChatFriendEntity chatFriend = new ChatFriendEntity();
                chatFriend.setUserId(operationUserId);
                chatFriend.setFriendId(userId);
                chatFriend.setStatus(FriendStatusEnum.TWO.getCode());
                chatFriend.setIsFriend(YesNoNumberEnum.NO.getCode());
                chatFriendManager.save(chatFriend);
            } else {
                oldChatFriend.setStatus(FriendStatusEnum.TWO.getCode());
                chatFriendManager.updateById(oldChatFriend);
            }
        }
        return removeFlag;
    }

    /**
     * 黑名单列表
     *
     * @Title:
     * @MethodName: blacklist
     * [query]
     * @Return java.util.List<com.xinqi.modules.chat.chat.friend.dto.rsp.ChatFriendBlackListDto>
     * @Exception
     * @Description:
     * @author: yyzhen
     * @date: 2023/3/10 10:29
     */
    @DS("slaver")
    @Override
    public List<ChatFriendBlackListDto> blacklist(ChatFriendBlackListDto query) {
        query.setStatus(FriendStatusEnum.TWO.getCode());
        return chatFriendManager.blacklist(query);
    }

    /**
     * 账号注销
     * 删除用户的所有好友
     *
     * @Title:
     * @MethodName: deleteFriendByUserId
     * [userId]ConversationSelectDTO
     * @Return java.lang.Boolean
     * @Exception
     * @Description:
     * @author: yyzhen
     * @date: 2023/3/10 14:41
     */
    @Override
    public Boolean deleteFriendByUserId(Long userId) {
        //好友方删除（改为非好友状态）
        LambdaUpdateWrapper<ChatFriendEntity> user = Wrappers.lambdaUpdate();
        user.set(ChatFriendEntity::getIsFriend, YesNoNumberEnum.NO.getCode())
            .eq(ChatFriendEntity::getFriendId, userId);
        chatFriendManager.update(user);
        //操作方删除（改为非好友状态）
        LambdaUpdateWrapper<ChatFriendEntity> friend = Wrappers.lambdaUpdate();
        friend.set(ChatFriendEntity::getIsFriend, YesNoNumberEnum.NO.getCode())
            .eq(ChatFriendEntity::getUserId, userId);

        return chatFriendManager.update(friend);
    }

    /**
     * 好友汇总列表只包含头像名称和会话ID
     *
     * @param dto
     * @return
     */
    @DS("slaver")
    @Override
    public List<ConversationResultDTO> selectConversation(ConversationSelectDTO dto) {
        dto.setStatus(FriendStatusEnum.ONE.getCode());
        dto.setIsFriend(YesNoNumberEnum.YES.getCode());
        return chatFriendManager.selectConversation(dto);
    }

    /**
     * 查询非群员的好友
     *
     * @param dto
     * @return
     */
    @DS("slaver")
    @Override
    public List<GroupUserFriendResultDTO> groupUserFriend(GroupUserFriendQueryDTO dto) {
        dto.setFriendStatus(FriendStatusEnum.ONE.getCode());
        dto.setIsFriend(YesNoNumberEnum.YES.getCode());
        return chatFriendManager.groupUserFriend(dto);
    }

    private LambdaQueryWrapper<ChatFriendEntity> wrapper(Long userId, Long id) {
        LambdaQueryWrapper<ChatFriendEntity> wrapper = Queries.lambda();
        Queries.accept(id, v -> wrapper.eq(ChatFriendEntity::getId, v));
        Queries.accept(userId, v -> wrapper.eq(ChatFriendEntity::getUserId, v));
        return wrapper;
    }

}
